package com.example.demo.controller;

import com.example.demo.entity.ApiResponse;
import com.example.demo.entity.Roles;
import com.example.demo.entity.User;
import com.example.demo.service.RolesService;
import com.example.demo.service.UserService;
import com.example.demo.utrl.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RolesService rolesService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    //    POST /api/users/register：用户注册接口，接收用户注册信息并返回注册结果。
    @PostMapping("/users/register")
    public ResponseEntity<ApiResponse> register(@RequestBody User user) {
        ApiResponse apiResponse;
        try {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            int result = userService.addUSer(user);
            if (result == 1) {
                apiResponse = new ApiResponse(1, "信息注册成功", null);
                return ResponseEntity.ok(apiResponse);
            } else {
                apiResponse = new ApiResponse(0, "信息注册失败", null);
                return ResponseEntity.status(500).body(apiResponse);
            }

        } catch (Exception e) {
            logger.info("接收数据{}", user);
            logger.error(e.getMessage());
            apiResponse = new ApiResponse(2, "信息注册失败", null);
            return ResponseEntity.status(500).body(apiResponse);
        }
    }

    //POST /api/users/login：用户登录接口，接收用户登录信息并返回登录状态和用户信息。
    @PostMapping("/users/login")
    public ResponseEntity<ApiResponse> login(@RequestBody User user) {
        ApiResponse apiResponse;
        try {
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            UserDetails userDetails =userDetailsService.loadUserByUsername(user.getUsername());
            String jwt =jwtTokenUtil.generateToken(userDetails);
            apiResponse = new ApiResponse(1, "登录成功", jwt);
            return ResponseEntity.ok(apiResponse);

        } catch (Exception e) {
            logger.error("接收数据{}", user);
            logger.error(e.getMessage());
            apiResponse = new ApiResponse(2, "登录失败", null);
            return ResponseEntity.status(500).body(apiResponse);
        }
    }

    //GET /api/users/{id}：获取用户信息接口，根据用户ID返回用户详细信息。
    @PreAuthorize("hasAuthority('user:read')")
    @GetMapping("/users/{id}")
    public ResponseEntity<ApiResponse> getUserDetails(@PathVariable("id") Integer id) {
        ApiResponse apiResponse;
        try {
            User result = userService.getUserDetails(id);
            if (result != null) {
                apiResponse = new ApiResponse(1, "获取用户信息成功", result);
                return ResponseEntity.ok(apiResponse);
            } else {
                apiResponse = new ApiResponse(0, "获取用户信息失败", null);
                return ResponseEntity.status(500).body(apiResponse);
            }

        } catch (Exception e) {
            logger.info("接收数据{}", id);
            logger.error(e.getMessage());
            apiResponse = new ApiResponse(2, "获取用户信息失败", null);
            return ResponseEntity.status(500).body(apiResponse);
        }
    }

    //PUT /api/users/{id}：更新用户信息接口，根据用户ID更新用户信息。
    @PreAuthorize("hasAuthority('user:update')")
    @PutMapping("/users/{id}")
    public ResponseEntity<ApiResponse> updateUser(@PathVariable("id") Integer id, @RequestBody User user) {
        ApiResponse apiResponse;
        try {
            user.setId(id);
            int result = userService.updateUser(user);
            if (result == 1) {
                apiResponse = new ApiResponse(1, "更新用户信息成功", null);
                return ResponseEntity.ok(apiResponse);
            } else {
                apiResponse = new ApiResponse(0, "更新用户信息失败", null);
                return ResponseEntity.status(500).body(apiResponse);
            }

        } catch (Exception e) {
            logger.info("接收数据{}", user);
            logger.error(e.getMessage());
            apiResponse = new ApiResponse(2, "更新用户信息失败", null);
            return ResponseEntity.status(500).body(apiResponse);
        }
    }

    //DELETE /api/users/{id}：删除用户接口，根据用户ID删除用户（需管理员权限）。
    @PreAuthorize("hasAuthority('user:delete')")
    @DeleteMapping("/users/{id}")
    public ResponseEntity<ApiResponse> delUser(@PathVariable("id") Integer user_id) {
        ApiResponse apiResponse;
        try {
            int result = userService.delUser(user_id);
            if (result == 1) {
                apiResponse = new ApiResponse(1, "删除用户成功", null);
                return ResponseEntity.ok(apiResponse);
            } else {
                apiResponse = new ApiResponse(0, "删除用户失败", null);
                return ResponseEntity.status(500).body(apiResponse);
            }

        } catch (Exception e) {
            logger.info("接收数据{}", user_id);
            logger.error(e.getMessage());
            apiResponse = new ApiResponse(2, "删除用户失败", null);
            return ResponseEntity.status(500).body(apiResponse);
        }
    }

    //    GET /api/users/roles：获取用户角色列表接口，返回所有用户角色信息。
    @GetMapping("/users/roles")
    @PreAuthorize("hasAuthority('role:read')")
    public ResponseEntity<ApiResponse> getRoles() {
        ApiResponse apiResponse;
        List<Roles> result;
        try {
            result = rolesService.getList();
            if (result != null) {
                apiResponse = new ApiResponse(1, "获取用户角色列表成功", result);
                return ResponseEntity.ok(apiResponse);
            } else {
                apiResponse = new ApiResponse(0, "获取用户角色列表失败", null);
                return ResponseEntity.status(500).body(apiResponse);
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            apiResponse = new ApiResponse(2, "获取用户角色列表失败", null);
            return ResponseEntity.status(500).body(apiResponse);
        }
    }

    //POST /api/users/roles：创建用户角色接口，接收角色信息并创建新角色。
    @PostMapping("/users/roles")
    @PreAuthorize("hasAuthority('role:create')")
    public ResponseEntity<ApiResponse> addRoles(@RequestBody Roles roles) {
        ApiResponse apiResponse;
        try {
            int result = rolesService.createRoles(roles);
            if (result == 1) {
                apiResponse = new ApiResponse(1, "创建用户角色成功", null);
                return ResponseEntity.ok(apiResponse);
            } else {
                apiResponse = new ApiResponse(0, "创建用户角色失败", null);
                return ResponseEntity.status(500).body(apiResponse);
            }

        } catch (Exception e) {
            logger.info("接收数据{}", roles);
            logger.error(e.getMessage());
            apiResponse = new ApiResponse(2, "创建用户角色失败", null);
            return ResponseEntity.status(500).body(apiResponse);
        }
    }

    //PUT /api/users/roles/{id}：更新用户角色接口，根据角色ID更新角色信息。
    @PutMapping("/users/roles/{id}")
    @PreAuthorize("hasAuthority('role:update')")
    public ResponseEntity<ApiResponse> updateRoles(@PathVariable("id") Integer id, @RequestBody Roles roles) {
        ApiResponse apiResponse;
        try {
            roles.setId(id);
            int result = rolesService.updateRoles(roles);
            if (result == 1) {
                apiResponse = new ApiResponse(1, "更新用户角色成功", null);
                return ResponseEntity.ok(apiResponse);
            } else {
                apiResponse = new ApiResponse(0, "更新用户角色失败", null);
                return ResponseEntity.status(500).body(apiResponse);
            }

        } catch (Exception e) {
            logger.info("接收数据{}", roles);
            logger.error(e.getMessage());
            apiResponse = new ApiResponse(2, "更新用户角色失败", null);
            return ResponseEntity.status(500).body(apiResponse);
        }
    }

    //DELETE /api/users/roles/{id}：删除用户角色接口，
    @PreAuthorize("hasAuthority('role:delete')")
    @DeleteMapping("/users/roles/{id}")
    public ResponseEntity<ApiResponse> delRoles(@PathVariable("id") Integer roles_id) {
        ApiResponse apiResponse;
        try {
            int result = rolesService.delRoles(roles_id);
            if (result == 1) {
                apiResponse = new ApiResponse(1, "删除用户角色成功", null);
                return ResponseEntity.ok(apiResponse);
            } else {
                apiResponse = new ApiResponse(0, "删除用户角色失败", null);
                return ResponseEntity.status(500).body(apiResponse);
            }

        } catch (Exception e) {
            logger.info("接收数据{}", roles_id);
            logger.error(e.getMessage());
            apiResponse = new ApiResponse(2, "删除用户角色失败", null);
            return ResponseEntity.status(500).body(apiResponse);
        }
    }
}
